<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
  {
    style: {
      navigationBarTitleText: '首页',
    },
  }
  </route>
<template>
  <view class="overflow-hidden p-2 contarnier">
    <wd-swiper v-if="advertisementList.length" :list="advertisementList" autoplay></wd-swiper>

    <view class="mt-4" v-if="noticeList.length">
      <wd-notice-bar :text="noticeList[0].advertisementName" prefix="warn-bold" />
    </view>

    <view class="mt-4" v-if="[1, 2, 3].includes(userInfo?.role)">
      <wd-card custom-class="custtom_card">
        <view class="flex justify-center mt-6">
          <wd-text color="black" size="24px" :text="moneyTotal" mode="price" bold prefix="￥" />
        </view>

        <template #title>
          <view style="display: flex; align-items: center; width: 100%; justify-content: center">
            <wd-text type="primary" text="今日总收益"></wd-text>
            <wd-icon class="ml-1" name="refresh1" size="20px" color="#4d80f0" @click="getStatistics"></wd-icon>
          </view>
        </template>
      </wd-card>
    </view>

    <view class="mt-4" style="border-radius: 10px; background-color: white">
      <wd-grid :column="4" clickable style="border-radius: 10px">
        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" custom-class="custom-item"
          use-icon-slot icon="picture" text="设备中心" @itemclick="goToDeviceCenter">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/Group 2678.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item v-if="[1, 2].includes(userInfo?.role)" icon-size="35px" custom-class="custom-item" use-icon-slot
          icon="picture" text="设备注册" @itemclick="registerDevice">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/Group 2681.png" />
          </template>
        </wd-grid-item>
        <wd-grid-item v-if="[3].includes(userInfo?.role)" icon-size="35px" use-icon-slot icon="picture" text="套餐设置"
          @itemclick="goPackageSetting">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/Group 2682.png" />
          </template>
        </wd-grid-item>
        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" use-icon-slot icon="picture"
          text="订单查询" @itemclick="goOrderQuery">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/Group 2683.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item v-if="[1].includes(userInfo?.role)" icon-size="35px" use-icon-slot icon="picture"
          text="商户查询" @itemclick="goMerchantQuery">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/shop.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item v-if="[1, 2].includes(userInfo?.role)" icon-size="35px" use-icon-slot icon="picture"
          text="个人资料" @itemclick="goToProfile">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/tabbar/personal.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item icon-size="35px" use-icon-slot icon="picture" text="营业汇总" @itemclick="goBusinessSummary"
          v-if="[1, 2, 3].includes(userInfo?.role)">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/password.png" />
          </template>
        </wd-grid-item>
        <!-- <wd-grid-item icon-size="35px" use-icon-slot icon="picture" text="快速购币" @itemclick="goToBuyGame">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/game.png" />
          </template>
        </wd-grid-item> -->
        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" use-icon-slot icon="picture"
          text="远程补币" @itemclick="goToBuyRemote">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/yuancheng.png" />
          </template>
        </wd-grid-item>
        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" custom-class="custom-item"
          use-icon-slot icon="picture" text="自主进件" @itemclick="jinjian">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/images/jinjian.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" custom-class="custom-item"
          use-icon-slot icon="picture" text="商家认证码" @itemclick="goToMerchantCode">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/rz.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item v-if="[1, 2, 3].includes(userInfo?.role)" icon-size="35px" custom-class="custom-item"
          use-icon-slot icon="picture" text="进件教程" @itemclick="goToTutorial">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/images/jc.png" />
          </template>
        </wd-grid-item>

        <wd-grid-item icon-size="35px" custom-class="custom-item" use-icon-slot icon="picture" text="联系客服"
          @itemclick="goToService">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/images/kefu.png" />
          </template>
        </wd-grid-item>


        <!-- <wd-grid-item
            v-if="[1, 3].includes(userInfo?.role)"
            icon-size="35px"
            use-icon-slot
            icon="picture"
            text="代理管理"
            @itemclick="goToProxy"
          >
            <template #icon>
              <image style="width: 35px; height: 35px" src="@/static/home/proxy.png" />
            </template>
          </wd-grid-item>
  
          <wd-grid-item
            v-if="[1].includes(userInfo?.role)"
            icon-size="35px"
            use-icon-slot
            icon="picture"
            text="商家管理"
          >
            <template #icon>
              <image style="width: 35px; height: 35px" src="@/static/home/shop.png" />
            </template>
          </wd-grid-item> -->

        <wd-grid-item icon-size="35px" use-icon-slot icon="picture" text="退出登陆" @itemclick="logout">
          <template #icon>
            <image style="width: 35px; height: 35px" src="@/static/home/pie_chart_128px.png" />
          </template>
        </wd-grid-item>
      </wd-grid>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { httpGet, httpPost } from '@/utils/http'
import { onShow } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
defineOptions({
  name: 'Home',
})

const moneyTotal = ref(0)

// 获取统计信息
const getStatistics = async () => {
  const _res: any = await httpPost('/api/app/order/order/statisticsByDate', {
    // 当天的0点
    startTime: dayjs().startOf('day').format('YYYY-MM-DD'),
    endTime: dayjs().format('YYYY-MM-DD'),
  })

  let _money = 0


  _res?.forEach((item) => {
    _money += item.totalAmount
  })

  moneyTotal.value = (_money * 1) / 100
}

// 轮播图列表
const advertisementList = ref<any[]>([])
// 通告列表
const noticeList = ref<any[]>([])
// 获取广告列表
const getAdvertisementList = async () => {
  const _res: any = await httpPost('/api/app/advertisement/index/list', {})

  advertisementList.value = _res
    .filter((item: any) => item.advertisementType === 0)
    ?.map((_r) => _r?.advertisementImg)

  noticeList.value = _res.filter((item: any) => item.advertisementType === 1)
}

const userInfo: any = ref({})

const getUserInfo = async () => {
  const _res = await httpGet('/api/app/user/info/person')

  // role // 0: 普通用户, 1: 代理, 2: 商户, 3: 平台
  userInfo.value = _res
}

getStatistics()

getAdvertisementList()

// 获取用户信息
getUserInfo()

/* 合同信息 */
const contractData = ref<any>()

/* 获取当前用户是否有进件中 */
const getApplying = async () => {
  const _res = await httpPost('/api/app/lakala/merchant/isApplying')
  console.log('getApplyinggetApplying,', _res)

  contractData.value = _res
}

getApplying()

const goToDeviceCenter = () => {
  uni.navigateTo({
    url: '/pages/index/device/index',
  })
}

const goBusinessSummary = () => {
  uni.navigateTo({
    url: '/pages/index/businessSummary/index',
  })
}

// 绑定设备
const bindDevice = async (deviceNo) => {
  try {
    uni.showLoading({
      title: '绑定中',
      mask: true,
    })
    await httpPost('/api/app/device/device/addDevice', {
      deviceNo,
    })
    uni.hideLoading()

    uni.showModal({
      title: '绑定成功',
      icon: 'none',
      confirmButtonText: '确定',
      showCancel: false,
    })
  } catch (error) {
    uni.hideLoading()
    // uni.showModal({
    //   title: error?.data?.message,
    //   icon: 'none',
    //   confirmButtonText: '确定',
    //   showCancel: false,
    // })
  }
}
// 前往设备注册页
const registerDevice = () => {
  wx.scanCode({
    success: (res) => {
      console.log('res,', res)
      const _no = res.result.split('?')[1].split('=')[1]

      if (_no) {
        bindDevice(_no)
      } else {
        uni.showModal({
          title: '设备码无效',
          icon: 'none',
          confirmButtonText: '确定',
          showCancel: false,
        })
      }

      // uni.navigateTo({
      //   url: '/pages/index/deviceRegister/index' + `?deviceNo=${_no}`,
      // })
    },
  })
}

// 前往订单查询页
const goOrderQuery = () => {
  uni.navigateTo({
    url: '/pages/index/order/index',
  })
}

const goMerchantQuery = () => {
  uni.navigateTo({
    url: '/pages/index/merchantSummary/index',
  })
}

// 前往套餐设置页
const goPackageSetting = () => {
  uni.navigateTo({
    url: '/pages/index/package/index',
  })
}

const logout = () => {
  // 清空localStorage
  uni.clearStorage()
  // 跳到登陆页
  uni.navigateTo({
    url: '/pages/login/index',
  })
}


const jinjian = () => {
  uni.navigateTo({
    url: '/pages/merchantApply/index',
  })
}

// 跳到商家认证码页面
const goToMerchantCode = () => {
  uni.navigateTo({
    url: '/pages/merchantCode/index'
  })
}

// 跳到教程
const goToTutorial = () => {
  uni.navigateTo({
    url: '/pages/tutorial/index'
  })
}

// 跳到客服
const goToService = () => {
  uni.navigateTo({
    url: '/pages/service/index'
  })
}

const goToBuyGame = () => {
  // 扫码
  uni.scanCode({
    success: (res) => {
      console.log('res,', res)
      // 从"https://ryxkeji.com/#/pages/index/buyGame/index?deviceNo=860835085785846"，提取出deviceNo
      const _no = res.result.split('?')[1].split('=')[1]
      console.log('deviceNo,', _no)
      // deviceNo.value = _no

      uni.navigateTo({
        url: '/pages/index/buyGame/index' + `?deviceNo=${_no}`,
        success: function (res) {
          console.log(res)
        },
        fail: function (res) {
          console.log(res)
        },
      })
    },
  })
}

// 跳到远程购币
const goToBuyRemote = () => {
  uni.navigateTo({
    url: '/pages/index/buyGame/remote',
    success: function (res) {
      console.log(res)
    },
    fail: function (res) {
      console.log(res)
    },
  })
}

const goToProfile = () => {
  uni.navigateTo({
    url: '/pages/index/profile/index',
  })
}

// 一进页面，如果没登陆，自动进行登陆
onShow(() => {
  let _code = ''

  // 判断缓存是否有openId
  if (uni.getStorageSync('APP_OPEN_ID')) {
    return
  }

  wx.login({
    success: (res) => {
      console.log('res,', res)

      _code = res.code

      wx.getUserInfo({
        success: async function (res) {
          console.log(res.encryptedData) // 这是加密数据
          console.log(res.iv) // 解密算法的初始向量

          // 调用后端接口，进行登陆
          const _result = await httpPost('/api/app/user/login/mini', {
            code: _code,
            encryptedData: res.encryptedData,
            iv: res.iv,
          })

          console.log('_result_result_result_result', _result)

          // 本地缓存起来
          uni.setStorageSync('APP_OPEN_ID', (_result as any)?.openid)

          console.log('_result', _result)
        },
      })
    },
  })
})
</script>

<style>
/* 当前页面的page高度是100% */
.contarnier {
  height: 100%;
}

.main-title-color {
  color: #d14328;
}

.custtom_card {
  margin: 0 !important;
}

:deep(.custom-item) {
  text-align: center !important;

  display: flex;
  flex-direction: column;
}
</style>